package com.qf.dao.impl;

import com.alibaba.druid.sql.dialect.postgresql.visitor.PGEvalVisitor;
import com.qf.dao.BookDao;
import com.qf.entity.Book;
import com.qf.util.DruidUtil;
import com.qf.util.Page;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.QEncoderStream;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/*
杨威
2021/9/19
18:33
*/
public class BookDaoImpl implements BookDao {
    QueryRunner queryRunner = new QueryRunner();

    @Override
    public List<Book> selectAll() {
        String sql = "select * from book";
        try {
            List<Book> query = queryRunner.query(DruidUtil.getConnection(), sql, new BeanListHandler<>(Book.class));
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public List<Book> selectAllByPage(Page page) {
        String sql = "select * from book limit ?,?";
        Object[] params = {page.getStartRow(), page.getPageSize()};
        List<Book> books = null;
        try {
            books = queryRunner.query(DruidUtil.getConnection(), sql, new BeanListHandler<>(Book.class), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return books;
    }

    @Override
    public Long selectCount() {
        String sql="select count(*) from book";
        Long query=null;
        try {
            query = (Long)queryRunner.query(DruidUtil.getConnection(), sql, new ScalarHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }
}
